package org.chameleon.limit.factory;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.chameleon.lang.ConfigAbleManager;
import org.chameleon.datasource.factory.AbsDynamicCacheFactory;
import org.chameleon.limit.entity.RateLimiterConfig;
import org.chameleon.limit.limiter.CRateLimiter;


public abstract class AbsRateLimiterFactory extends AbsDynamicCacheFactory<RateLimiterConfig, CRateLimiter> {


    private static final String CACHE_PREFIX = "LimiterFactory:";

    public AbsRateLimiterFactory(ConfigAbleManager<RateLimiterConfig> manager) {
        super(manager);
    }

    public AbsRateLimiterFactory() {
    }

    public abstract CRateLimiter createRateLimiter(RateLimiterConfig config);


    @Override
    public CRateLimiter create(RateLimiterConfig rateLimiterConfig) {
        checkArguments(rateLimiterConfig);
        return createRateLimiter(rateLimiterConfig);

    }

    @Override
    public String getCacheKey(RateLimiterConfig rateLimiterConfig) {
        return CACHE_PREFIX + rateLimiterConfig.getGroup() + ":" + rateLimiterConfig.getKey();
    }


    private void checkArguments(RateLimiterConfig rateLimiterConfig) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(rateLimiterConfig.getGroup()), "限流器分组group不能为空");
        Preconditions.checkArgument(!Strings.isNullOrEmpty(rateLimiterConfig.getKey()), "限流器项目key不能为空");
    }


}
